package activity

import (
	"context"
	"encoding/json"

	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/logic/promotion/util"
	"mall/service/backend/api/internal/logic/utils"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	enum "mall/service/backend/common/enum/promotion"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/promotion/rpc/promotionclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetPromotionActivityByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetPromotionActivityByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPromotionActivityByIdLogic {
	return &GetPromotionActivityByIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetPromotionActivityByIdLogic) GetPromotionActivityById(req *types.IDReq) (*types.PromotionActivityInfoResp, error) {
	if req.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	data, err := l.svcCtx.PromotionRpc.BackendGetActivityById(l.ctx, &promotionclient.ActivityIdReq{
		Id:        req.Id,
		WithRules: pointy.GetPointer(uint32(1)),
		WithMeta:  pointy.GetPointer(uint32(1)),
		WithMedia: pointy.GetPointer(uint32(1)),
	})
	if err != nil {
		return nil, err
	}

	var meta []*types.MetaInfo
	if len(data.Meta) > 0 {
		for _, v := range data.Meta {
			meta = append(meta, &types.MetaInfo{
				Id:    v.Id,
				Key:   v.Key,
				Value: v.Value,
			})
		}
	}

	var media []*types.MediaInfo
	if len(data.Media) > 0 {
		for _, v := range data.Media {
			var url string
			if v.Url != nil && len(*v.Url) > 0 {
				url = *v.Url
			}
			if len(url) == 0 && v.Uri != nil && len(*v.Uri) > 0 {
				url = *v.Uri
			}
			filename, mimeType, metaData := utils.ParseMetaData(v.MetaData)
			media = append(media, &types.MediaInfo{
				Uid:       v.Uid,
				Id:        v.Id,
				Thumbnail: v.Thumbnail,
				Order:     v.Order,
				Url:       pointy.GetPointer(url),
				Name:      pointy.GetPointer(filename),
				MimeType:  pointy.GetPointer(mimeType),
				AltText:   v.AltText,
				MetaData:  pointy.GetPointer(metaData),
			})
		}
	}

	var mustBind bool
	var canBind bool
	if data.Step != nil && data.ScopeType != nil && uint8(*data.ScopeType) > enum.PromotionScopeAll {
		switch uint8(*data.Step) {
		case enum.PromotionActivityStepBasic:
			mustBind = true
			canBind = true
		case enum.PromotionActivityStepMain, enum.PromotionActivityStepGift:
			canBind = true
		}
	}
	option := util.GetOptionByStatus(data.Status, mustBind, canBind)

	var groups []*types.PromotionActivityRuleGroupInfo
	var condition *uint32
	var conditionValue *string
	var discountMode *uint32
	var discountValue *string
	if len(data.Groups) > 0 {
		for _, v := range data.Groups {
			var rules []*types.PromotionActivityRuleInfo
			if len(v.Rules) > 0 {
				for _, vv := range v.Rules {
					var regions []*types.TreeNode
					if vv.Regions != nil {
						if err := json.Unmarshal([]byte(*vv.Regions), &regions); err != nil {
							logx.Errorw("GetPromotionActivityById Rules.Regions json.Unmarshal err", logx.Field("detail", err.Error()))
						}
					}

					if len(data.Groups) == 1 && len(v.Rules) == 1 {
						condition = vv.RuleType
						conditionValue = v.Threshold
						discountMode = vv.Mode
						discountValue = vv.Value
					}

					rules = append(rules, &types.PromotionActivityRuleInfo{
						BaseIDInfo: types.BaseIDInfo{
							Id: vv.Id,
						},
						ActivityId: vv.ActivityId,
						GroupId:    vv.GroupId,
						Regions:    regions,
						RuleType:   vv.RuleType,
						Mode:       vv.Mode,
						Value:      vv.Value,
						Sort:       vv.Sort,
						Status:     vv.Status,
					})
				}
			}

			groups = append(groups, &types.PromotionActivityRuleGroupInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id: v.Id,
				},
				ActivityId: v.ActivityId,
				Threshold:  v.Threshold,
				Sort:       v.Sort,
				Status:     v.Status,
				Rules:      rules,
			})
		}
	}

	return &types.PromotionActivityInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: &types.PromotionActivityInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:         data.Id,
				CreatedAt:  data.CreatedAt,
				UpdatedAt:  data.UpdatedAt,
				DeletedAt:  data.DeletedAt,
				CanAccept:  option.CanAccept,
				CanReject:  option.CanReject,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			Name:     data.Name,
			Slug:     data.Slug,
			DescHtml: data.Desc,
			Desc:     data.FilteredDesc,
			Status:   data.Status,
			Sort:     data.Sort,
			Meta:     meta,
			Media:    media,

			MemberRestriction:     data.MemberRestriction,
			ActivityType:          data.ActivityType,
			MutexType:             data.MutexType,
			ScopeType:             data.ScopeType,
			Condition:             condition,
			ConditionValue:        conditionValue,
			DiscountMode:          discountMode,
			DiscountValue:         discountValue,
			TimesLimit:            data.TimesLimit,
			GroupMode:             data.GroupMode,
			GroupType:             data.GroupType,
			SeckillLimit:          data.SeckillLimit,
			SeckillCancelDuration: data.SeckillCancelDuration,
			SeckillNotifyDuration: data.SeckillNotifyDuration,
			PackageType:           data.PackageType,
			PackagePicId:          data.PackagePicId,
			PackagePicUrl:         data.PackagePicUrl,
			StartedAt:             data.StartedAt,
			EndedAt:               data.EndedAt,
			Groups:                groups,
			MustBind:              option.MustBind,
			CanBind:               option.CanBind,
		},
	}, nil
}
